<template>
    <h2>-------------options API-----------------</h2>
    <div>{{ store1.count }}/{{ store1.double }}</div>
    <button @click="store1.increment(1)">修改状态</button>
    <button @click="() => increment1(2)">修改状态</button>
    <button @click="handleClick1">$patch-option 更新状态</button>
    <button @click="handleReset1">重置状态</button>
    <button @click="handleDispose">卸载响应式</button>
    <div>{{ count }}/{{ double }}</div>
    <h2>-------------setup API ------------------</h2>
    <div>{{ store2.count }}/{{ store2.double }}</div>
    <button @click="store2.increment()">修改状态</button>
    <button @click="() => increment2(3)">修改状态</button>
    <button @click="handleClick2">$patch-setup 更新状态</button>
    <button @click="handleClick3">更新整个状态</button>
    <hr />
    <About />
</template>

<script setup>
import About from "@/components/About.vue";
import { useCounterStore1 } from "./stores/counter1";
import { useCounterStore2 } from "./stores/counter2";
// import { storeToRefs } from "@/pinia";
import { storeToRefs } from "pinia";
const { increment: increment1 } = useCounterStore1(); // 解构 this 还是执行 store
const { increment: increment2 } = useCounterStore2();

const store1 = useCounterStore1();
// 解构获取响应式数据
const { count, double } = storeToRefs(store1);

// console.log(store1);
const handleClick1 = () => {
    store1.$patch({
        count: 100, // 设置需要更新状态的值
    });
};
const handleReset1 = () => {
    store1.$reset();
};
const handleDispose = () => {
    store1.$dispose(); // 计算属性则将不会改变
    // store1._p._e.stop();  官方给出终止全部的 store (不推荐使用)
};

const store2 = useCounterStore2();
// console.log(store2);
const handleClick2 = () => {
    store2.$patch((state) => {
        state.count = 200; // state 为旧的值可以赋值进行修改
    });
};
const handleClick3 = () => {
    console.log(store2.$state); // 获取到 store 中 state 值
    store2.$state = { count: 500, number: 50 };
};
// 监听状态变化
store2.$subscribe(function (storeInfo, state) {
    console.log(storeInfo);
    console.log(state);
});
// 监听方法(可以进行多次)(注意$patch更改数据监听不到)
store2.$onAction(function ({ after, onError }) {
    console.log("action running", store2.count); // 更新前的状态
    // after 可以多个
    after(() => {
        console.log("action after", store2.count); // 更新后的状态
    });
    after(() => {
        console.log("action after", store2.count);
    });
    // 发送错误触发
    onError((err) => {
        console.log("error", err);
    });
});
store2.$onAction(function ({ after, onError }) {
    console.log("action running", store1.count); // 更新前的状态
    after(() => {
        console.log("action after", store1.count); // 更新后的状态
    });
    onError((err) => {
        console.log("error", err);
    });
});
</script>

<style scoped></style>
